package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Transactional
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    private String webSite; //oss域名

    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.检查分页参数设置默认值
        dto.checkParam();

        //3.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //4.根据参数值动态拼接查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(dto.getStatus()!=null){
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus()); //动态拼接条件：根据状态查询
        }
        if(dto.getChannelId()!=null){
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId()); //动态拼接查询条件：根据频道ID查询
        }
        if(StringUtils.isNotBlank(dto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword()); //动态拼接查询条件：根据标题模糊查询
        }
        if(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());// 动态拼接查询条件： 根据发布时间范围查询
        }
        //5.拼接固定查询条件，按照创建时间倒排
        lambdaQueryWrapper.eq(WmNews::getUserId, wmUser.getId()); //固定查询条件：根据当前登录用户ID查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //6.执行分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        this.page(page,lambdaQueryWrapper);

        //7.封装分页响应结果数据并设置OSS域名
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        responseResult.setHost(webSite); //这里设置OSS域名，拼接域名工作交给前端处理

        //8.响应数据
        return responseResult;
    }


    @Override
    public ResponseResult submit(WmNewsDto dto, Short isSubmit) {

        //第一部分：准入控制
        //1.1 判断参数合法性
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.2 判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


        //第二部分：修改或创建文章
        //2.1 将dto复制给wmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);

        //2.2 判断当前布局方式如果是自动布局，暂时设置为空布局
        if(wmNews.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }

        //2.3 判断如果dto封面列表有值，那么遍历列表就去除域名前缀，并转为逗号分割的字符串
        /**
         * 举例：
         * 1）假如dto中images的值是如下这样：
         * "images":[ "https://hmleadnews.oss-cn-beijing.aliyuncs.com/material/2021/5/20210520/3ac77c9e4dcf4bbf91e34c5fa6465894.png",
         * "https://hmleadnews375.oss-cn-beijing.aliyuncs.com/material/2021/5/20210520/5227811087e8451f80282f7b12fa87c3.png"   ],
         *
         * 2）需要将如上图片列表转为逗号分割字符串，如下：
         * "material/2021/5/20210520/3ac77c9e4dcf4bbf91e34c5fa6465894.png,material/2021/5/20210520/5227811087e8451f80282f7b12fa87c3.png"
         */
        if(dto.getImages()!=null && dto.getImages().size()>0){
            List<String> coverImageList = dto.getImages().stream().map(x -> x.replace(webSite, "").replace(" ", "")).collect(Collectors.toList());
            String coverImageStr = StringUtils.join(coverImageList, ",");
            wmNews.setImages(coverImageStr);
        }

        //2.4 调用创建或修改文章
        ResponseResult responseResult = saveOrUpdateWmNews(wmNews, isSubmit);
        if(responseResult!=null){
            return responseResult;
        }

        //准备工作：抽取正文中的图片地址列表（去除域名前缀）
        List<String> contentImageList = extractContentImageList(wmNews.getContent());

        //第三部分：保存内容图片与文章的关系（执行前提：当前是提交审核且内容中图片地址列表有值）
        if(isSubmit.equals(WmNews.Status.SUBMIT.getCode()) && contentImageList.size()>0){
            responseResult = saveRelationForContent(contentImageList, wmNews.getId());
            if(responseResult!=null){
                return responseResult;
            }
        }


        //第四部分：保存封面图片与文章的关系（执行前提：当前是提交审核）
        if(isSubmit.equals(WmNews.Status.SUBMIT.getCode()) ){
            responseResult = saveRelationForCover(contentImageList, wmNews, dto);
            if(responseResult!=null){
                return responseResult;
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //保存封面图片与文章的关系，指明图片与文章的关系属于主图引用类型
    private ResponseResult saveRelationForCover(List<String> contentImageList, WmNews wmNews, WmNewsDto dto) {
        //1.获取封面地址列表
        List<String> coverImageList = dto.getImages();

        //2.判断当前封面布局方式，如果是自动布局，那么封面图片从内容图片列表中取用
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            int size = contentImageList.size();
            if(size>=3){ //当前内容图片数量如果大于等于3，则取3张图片当做封面图片，设置布局方式为多图布局
                coverImageList = contentImageList.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE); //多图布局
            } else if(size>=1 && size<3){ //当前内容图片数量如果大于等于1小于3，则取1张图片当做封面图片，设置布局方式为单图布局
                coverImageList = contentImageList.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE); //多图布局
            } else {
                coverImageList = new ArrayList<>(); //当前内容图片数量如果等于0，设置布局方式为无图布局
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE); //无图布局
            }

            //如果最终封面图片地址有值，那么就去除域名前缀转为逗号分割字符串
            if(coverImageList.size()>0){
                coverImageList = coverImageList.stream().map(x->x.replace(webSite,"").replace(" ","")).collect(Collectors.toList());
                String coverImageStr = StringUtils.join(coverImageList, ",");
                wmNews.setImages(coverImageStr);
            }

            //更新自媒体文章
            updateById(wmNews);

        }


        //3.无论当前是否是自动布局，都要判断封面图片地址列表是否有值后，再保存与文章的关系
        if(coverImageList!=null && coverImageList.size()>0){
            coverImageList= coverImageList.stream().map(x -> x.replace(webSite, "").replace(" ", "")).collect(Collectors.toList());
            ResponseResult responseResult = saveRelation(coverImageList, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
            if(responseResult!=null){
                return responseResult;
            }
        }

        return null;
    }

    //保存内容图片与文章的关系，指明图片与文章的关系属于内容引用类型
    private ResponseResult saveRelationForContent(List<String> contentImageList, Integer newId) {
        ResponseResult responseResult = saveRelation(contentImageList, newId, WemediaConstants.WM_CONTENT_REFERENCE);
        if(responseResult!=null){
            return responseResult;
        }
        return null;
    }


    @Autowired
    private WmMaterialMapper wmMaterialMapper;


    /**
     * 公共方法：目的在于保存素材与文章的关联关系
     * @param imageList  素材的地址列表
     * @param newsId  文章ID
     * @param type 引用类型，0-内容引用 1-主图引用
     * @return
     */
    private ResponseResult saveRelation(List<String> imageList, Integer newsId, Short type) {
        //1.根据图片地址列表当做IN查询条件去素材表中查询素材列表
        List<WmMaterial> materialList = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageList));


        //2.找出没有查到素材数据的素材地址（举例：如果有3个素材地址到素材表查询到2条素材记录，说明有一个素材地址没查询到数据，直接响应错误）
        //2.1 将素材列表转为MAP，其中key是URL、value是ID
        Map<String, Integer> materialsMap = materialList.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        //2.2 遍历素材地址列表，将每个遍历的地址当做KEY去map中查询，如果查不到数据，说明就找到了没有查到素材数据的这个地址

        List<Integer> materialIdList = new ArrayList<>();
        for (String imageUrl : imageList) {
            Integer materialId = materialsMap.get(imageUrl);
            if(materialId==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "素材数据不存在,imageUrl:" + imageUrl);
            }

            //3.收集所有素材的ID，封装到ID列表中
            materialIdList.add(materialId);
        }


        //4.调用mapper保存素材ID列表与文章的关系
        wmNewsMaterialMapper.saveRelationsByContent(materialIdList, newsId, type);
        return null;

    }

    //抽取正文中的图片地址列表（去除域名前缀）
    private List<String> extractContentImageList(String content) {
        List<String> contentImageList = new ArrayList<>();
        if(StringUtils.isNotBlank(content)){
            List<Map> mapList = JSON.parseArray(content, Map.class);
            if(mapList!=null && mapList.size()>0){
                for (Map<String,String> map : mapList) {
                    String type = map.get("type");
                    if(type.equals("image")){
                        String imageUrl = map.get("value");
                        if(imageUrl.startsWith(webSite)){
                            imageUrl = imageUrl.replace(webSite,"").replace(" ","");
                        }
                        contentImageList.add(imageUrl);
                    }
                }
            }
        }
        return contentImageList;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    //创建或修改文章
    private ResponseResult saveOrUpdateWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId()); //用户ID
        wmNews.setEnable((short)1); //默认已上架
        wmNews.setStatus(isSubmit); //0-保存草稿  1-提交审核
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());

        //1.如果文章已存在，就修改文章删除引用关系
        if(wmNews.getId()!=null && wmNews.getId()>0){
            WmNews wmNewsDB = getById(wmNews.getId());
            if(wmNewsDB==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
            }

            //删除引用关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

            //执行更新文章
            updateById(wmNews);

        } else {
            //2.如果文章不存在，就创建文章
            save(wmNews);
        }
        return null;
    }


    @Override
    public ResponseResult findOne(Integer id) {
        //1.判断参数合法性
        if(id==null || id==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.判断数据是否存在
        WmNews wmNews = getById(id);
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //4.封装响应数据设置OSS域名
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(webSite);  //这里设置OSS域名，拼接域名工作交给前端处理

        //5.响应数据
        return responseResult;
    }


    @Override
    public ResponseResult delOne(Integer id) {
        //1.判断参数合法性
        if(id==null || id==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.判断数据是否存在
        WmNews wmNews = getById(id);
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //4.判断当前文章状态是否已上架已发布
        if(wmNews.getEnable().equals(WemediaConstants.WM_NEWS_ENABLE_UP) && wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR, "当前文章不可删除");
        }

        //5.删除关联关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,id));

        //6.删除文章
        removeById(id);

        //7.响应数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.判断参数合法性
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.判断数据是否存在
        WmNews wmNews = getById(dto.getId());
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //4.判断数据状态是否是已发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR, "必须已发布的文章才能上下架");
        }


        //5.执行修改上下架状态
        WmNews wmNewsDB = new WmNews();
        wmNewsDB.setId(dto.getId());
        wmNewsDB.setEnable(dto.getEnable());
        updateById(wmNewsDB);


        //6.响应数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
